/*
** Copyright (C) 2010 Calin Radoni
**
** This file is part of CHScanner.
**
** CHScanner is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** CHScanner is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with CHScanner. If not, see <http://www.gnu.org/licenses/>.
*/

#include "StdAfx.h"
#include "MFileData.h"

MFileData::MFileData(void)
{
}

MFileData::~MFileData(void)
{
}

//---------------------------------------------------------------------------

bool MFileData::WriteRawData(char* dataIn, unsigned int sizeIn)
{
	if(dataIn==NULL) return false;
	if(sizeIn==0) return false;

	fs.write(dataIn, sizeIn);
	if(fs.fail())
		return false;

	return true;
}

//---------------------------------------------------------------------------

bool MFileData::LoadFromFile(CString fileNameIn, unsigned int recSize)
{
	char *data;
	bool err;

	InternalInit();

	if(recSize==0) return false;

	fs.open((char*)(LPCSTR)fileNameIn, std::ios_base::in | std::ios_base::binary);
	if(fs.fail())
		return false;

	data = NULL;
	try{
		data = new char[recSize];
	}
	catch(...){
		data = NULL;
	}
	if(data==NULL){
		fs.close();
		return false;
	}

	err = false;
	while(!fs.eof() && !err){
		fs.read(data, recSize);
		//fs._Read_s(data, recSize, recSize);
		if(fs.fail()){
			if(!fs.eof()){
				// reading error
				err = true;
			}
		}
		else{
			err = !InternalProcessRecord(data, recSize);
		}
	}

	delete[] data;

	fs.close();

	return !err;
}

//---------------------------------------------------------------------------

bool MFileData::SaveToFile(CString fileNameIn)
{
	bool res;

	fs.open((char*)(LPCSTR)fileNameIn, std::ios_base::out);
	if(fs.fail())
		return false;

	res = InternalSave();

	fs.close();
	return res;
}

//---------------------------------------------------------------------------

void MFileData::InternalInit(void)
{
}

bool MFileData::InternalProcessRecord(char*, unsigned int)
{
	return true;
}

bool MFileData::InternalSave(void)
{
	return true;
}

//---------------------------------------------------------------------------
